package com.lwj.designpattern.singleton;

/**
 * @author wujilee
 * @date 2023/2/13
 *  懒汉式
 *  懒汉式的问题在与在多线程环境下,可能会出现多个实例
 */
public class Test {
    private static  volatile Test test;
    private Test() {
    }
    // 加载的时候静态内部类是不会被加载的
    private  static  class  Test01{
        private final  static  Test instance = new Test();
    }
    public static  Test getInstance1() throws InterruptedException {
        Thread.sleep(100L);
        return Test01.instance;
    }
//    public  static synchronized Test getInstance() throws InterruptedException {
//        if(test == null){
//            Thread.sleep(100L);
//            test = new Test();
//        }
//        return test;
//    }
    // 双重验证是非常不错的写法之一，但凡是多线程共享数据并且有可能更改该数据的情况下
    // 都可以使用这种写法
public  static  Test getInstance() throws InterruptedException {
    if(test == null){// 为了增加执行速度
        //  双重验证
        synchronized (Test.class){
            if(test == null){
                Thread.sleep(100L);
                test = new Test();
            }
        }

    }
    return test;
}

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                Test instance = null;
                try {
                    instance = Test.getInstance1();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(instance.hashCode() );
            }).start();
        }
    }
}
